package com.ming.service.strategy;

import com.ming.config.properties.FileUploadProperties;
import com.ming.service.strategy.impl.LocalFileUploadStrategy;
import com.ming.service.strategy.impl.OSSFileUploadStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 文件上传策略工厂
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FileUploadStrategyFactory {

    private final FileUploadProperties fileUploadProperties;

    private final LocalFileUploadStrategy localFileUploadStrategy;
    private OSSFileUploadStrategy ossFileUploadStrategy;

    /**
     * 根据配置获取文件上传策略
     * @return 文件上传策略实例
     */
    public FileUploadStrategy getStrategy() {
        String storageType = fileUploadProperties.getType();

        if ("local".equals(storageType)) {
            log.info("使用本地文件上传策略");
            return localFileUploadStrategy;
        } else if ("oss".equals(storageType)) {
            log.info("使用OSS文件上传策略");
            return getOssFileUploadStrategy();
        } else {
            throw new IllegalArgumentException("不支持的文件存储类型: " + storageType);
        }
    }

    /**
     * 获取OSS文件上传策略实例（延迟加载）
     */
    private FileUploadStrategy getOssFileUploadStrategy() {
        if (ossFileUploadStrategy == null) {
            synchronized (this) {
                if (ossFileUploadStrategy == null) {
                    // 这里需要从Spring容器获取，或者手动创建
                    // 由于使用了条件注解，可能在OSS配置不存在时这个Bean不会被创建
                    throw new IllegalStateException("OSS文件上传策略未配置或初始化失败，请检查OSS相关配置");
                }
            }
        }
        return ossFileUploadStrategy;
    }

    /**
     * 设置OSS文件上传策略实例（用于依赖注入）
     */
    @Autowired(required = false)
    public void setOssFileUploadStrategy(OSSFileUploadStrategy ossFileUploadStrategy) {
        this.ossFileUploadStrategy = ossFileUploadStrategy;
    }
}